package com.mti.monitor.service;

import com.mti.monitor.bean.model.SysDataSourceConfig;
import com.mti.monitor.bean.model.SysMonitorConfig;
import com.mti.monitor.bean.model.SysMonitorErrorLog;
import com.mti.monitor.config.DataSourceContextHolder;
import com.mti.monitor.config.DynamicDataSource;
import com.mti.monitor.mapper.SysDataSourceConfigMapper;
import com.mti.monitor.mapper.SysMonitorConfigMapper;
import com.mti.monitor.mapper.SysMonitorErrorLogMapper;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Log4j2
public class DataMonitorService {


    @Autowired
    private SysMonitorConfigMapper sysMonitorConfigMapper;
    @Autowired
    private SysMonitorErrorLogMapper sysMonitorErrorLogMapper;
    @Autowired
    private MessageService messageService;

    @Autowired
    private SysDataSourceConfigMapper sysDataSourceConfigMapper;
    @Autowired
    private DynamicDataSource dynamicDataSource;

    /**
     * 数据监控服务
     */
    public void monitorData(String monitorId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //切换默认数据源
        DataSourceContextHolder.clearDataSourceType();
        SysMonitorConfig config = sysMonitorConfigMapper.selectById(monitorId);
        if (!config.getUseYn()) {
            return;
        }
        String dataMonitorSql = config.getDataMonitorSql();
        log.info("开始执行数据检测任务【{}】", config.getTaskName());
        try {
            SysDataSourceConfig dataSource = sysDataSourceConfigMapper.selectById(config.getDataSourceId());
            //创建数据源连接&检查 若存在则不需重新创建
            dynamicDataSource.createDataSourceWithCheck(dataSource);
            //切换到该数据源
            DataSourceContextHolder.setDataSourceType(dataSource.getDataSourceId());

            int count = sysMonitorErrorLogMapper.queryCountBySql(dataMonitorSql);

            if (count == 0) {
                log.warn("{}数据检测数量是0！", config.getTaskName());
                String extStr = "";
                if (config.getLastTimeSql() != null && StringUtils.isNotEmpty(config.getLastTimeSql())) {
                    Date date = sysMonitorErrorLogMapper.queryTimeBySql(config.getLastTimeSql());
                    extStr = "，最后一条发送时间" + sdf.format(date);
                }

                DataSourceContextHolder.clearDataSourceType();
                messageService.sendAlarmMessage(config.getPhoneNumbers(), config.getMessageContent() + extStr, config.getMessageChannel());
                //添加本次异常记录
                SysMonitorErrorLog currentLog = new SysMonitorErrorLog();
                currentLog.setLogId(UUID.randomUUID().toString().replaceAll("-", ""));
                currentLog.setId(monitorId);
                currentLog.setExecuteTime(new Date());
                currentLog.setFailCount(1);
                currentLog.setSendMessageYn(true);
                currentLog.setMessageContent(config.getMessageContent() + extStr);
                currentLog.setPhoneNumbers(config.getPhoneNumbers());
                sysMonitorErrorLogMapper.insert(currentLog);

            } else {
                //切换默认数据源
                DataSourceContextHolder.clearDataSourceType();
                log.info("结束数据检测任务【{}】，检测结果数量：{}", config.getTaskName(), count);
            }

        } catch (Exception e) {
            //切换默认数据源
            DataSourceContextHolder.clearDataSourceType();
            log.error("数据检测任务【{}】在数据源{}上执行SQL有误：{}", config.getTaskName(), config.getDataSourceId(), dataMonitorSql);
            //执行数据检测任务报错，发送短信提示信息
            String errorMsg = "数据检测任务【" + config.getTaskName() + "】在数据源" + config.getDataSourceId() + "上执行失败！";
            messageService.sendAlarmMessage(config.getPhoneNumbers(), errorMsg, config.getMessageChannel());
            //添加本次异常记录
            SysMonitorErrorLog currentLog = new SysMonitorErrorLog();
            currentLog.setLogId(UUID.randomUUID().toString().replaceAll("-", ""));
            currentLog.setId(monitorId);
            currentLog.setExecuteTime(new Date());
            currentLog.setFailCount(1);
            currentLog.setSendMessageYn(true);
            currentLog.setMessageContent(errorMsg);
            currentLog.setPhoneNumbers(config.getPhoneNumbers());
            sysMonitorErrorLogMapper.insert(currentLog);
        }

    }
}
